package com.example.dense_rack_server.utils.DataBackup.quartz.job;

import com.alibaba.fastjson.JSONObject;
import com.example.dense_rack_server.entity.BackupLog;
import com.example.dense_rack_server.entityVo.dataBackup.BackupJobVO;
import com.example.dense_rack_server.enums.BackupCategoryEnum;
import com.example.dense_rack_server.service.dataBackup.BackupLogService;
import com.example.dense_rack_server.utils.DataBackup.MysqlTool;
import com.example.dense_rack_server.utils.DataBackup.quartz.QuartzManager;
import com.example.dense_rack_server.utils.DateFormat;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 备份定时任务job
 * @author asurplus
 */
@Slf4j
public class BackupJob implements Job {

    @Autowired
    private MysqlTool mysqlTool;

    @Autowired
    private BackupLogService backupLogService;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        // 解析参数
        BackupJobVO jobVO = JSONObject.parseObject(context.getJobDetail().getJobDataMap().getString(QuartzManager.PARAM_KEY), BackupJobVO.class);
        if (jobVO == null) {
            log.error("BackupJob参数解析失败");
            return;
        }
        // 保存备份记录
        BackupLog backupLog = backupLogService.saveBackupLog(jobVO, BackupCategoryEnum.AUTO);
        // 开始备份
        mysqlTool.saveBackUp(jobVO, backupLog);
        // 结束备份
        log.info("BackupJob执行成功，备份记录ID：{}, 备份时间：{}", backupLog.getId(), DateFormat.getTime());
    }

}
